package cn.itsource.user.service.impl;

import cn.itsource.basic.jwt.JwtUtil;
import cn.itsource.basic.jwt.Payload;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.UserAddress;
import cn.itsource.user.mapper.UserAddressMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：订单地址
 */
@Service
public class UserAddressServiceImpl extends BaseServiceImpl<UserAddress> implements IUserAddressService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;

    @Transactional
    @Override
    public AjaxResult saveUserAddress(UserAddress userAddress, HttpServletRequest request) {
       userAddress.setCreateTime(new Date());
       userAddress.setFullAddress(userAddress.getAreaCode() + userAddress.getAddress());
       userAddress.setPhoneBack(userAddress.getPhone());
       userAddress.setTel(userAddress.getPhone());

        String token = request.getHeader("token");
        Payload payload = JwtUtil.parseJwtToken(token);
        Logininfo logininfo = payload.getLogininfo();
        User user = userMapper.findByLogininfoId(logininfo.getId());
        userAddress.setUserId(user.getId());

        userAddressMapper.add(userAddress);
        return new AjaxResult();
    }

    @Transactional
    @Override
    public AjaxResult updateUserAddress(UserAddress userAddress, HttpServletRequest request) {
        userAddress.setUpdateTime(new Date());
        userAddress.setFullAddress(userAddress.getAreaCode() + userAddress.getAddress());
        userAddress.setPhoneBack(userAddress.getPhone());
        userAddress.setTel(userAddress.getPhone());
        userAddressMapper.update(userAddress);
        return new AjaxResult();
    }
}
